package org.graduation.IM.service.socket;

import com.corundumstudio.socketio.SocketIOClient;
import lombok.extern.slf4j.Slf4j;
import org.graduation.model.common.IM.GroupMessage;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public abstract class GroupSocketService extends SingleUserSocketService {
    protected Map<Long, Set<SocketIOClient>> groupMap = new ConcurrentHashMap<>();
    private final List<SocketIOClient> emptyGroupCache = new ArrayList<>();

    @Override
    public void login(Integer uid, SocketIOClient client) {
        super.login(uid, client);
        joinGroup(uid, client);
    }

    public void logout(Integer uid) {
        leaveGroup(uid);
        super.logout(uid);
    }

    /**
     * 加入群聊
     * 1.获取uid的groupId；
     * 2.根据groupId依次将用户添加到群聊中
     *
     * @param uid
     * @param socketIOClient
     */
    protected abstract void joinGroup(Integer uid, SocketIOClient socketIOClient);

    /**
     * 退出群聊
     * 1.获取uid的groupId；
     * 2.根据groupId依次将用户从群聊中移除
     *
     * @param uid
     */
    protected abstract void leaveGroup(Integer uid);

    /**
     * 发送群聊消息
     *
     * @param message
     */
    public abstract void sendGroupMessage(GroupMessage message);

    protected abstract boolean checkGroupUser(Long groupId, Integer uid);

    /**
     * 获取群在线用户
     *
     * @param groupId
     * @return
     */
    protected List<SocketIOClient> getGroupClient(Long groupId) {
        Set<SocketIOClient> userClients = groupMap.get(groupId);
        if (userClients == null) {
            return emptyGroupCache;
        }
        return new ArrayList<>(userClients);
    }
}
